#pragma once
#include <cstdio>
#include <string>
#include <filesystem> //C++17
#include <sstream>
#include <fstream>
#include <memory>
#include <ctime>
#include <unistd.h>
#include "Mutex.hpp"
#include<iostream>
namespace LogMoudle
{
    using namespace MutexMoudle;
    const std::string gsep = "\r\n";
    // 策略模式，C++多态特性
    // 2. 刷新策略 a: 显示器打印 b:向指定的文件写入
    //  刷新策略基类
    class LogManage
    {
    public:
        ~LogManage() = default;                               // 强制执行默认析构函数
        virtual void Synclog(const std::string &message) = 0; // 刷新方式纯虚函数，为派生类提供接口
    private:
    };
    // 显示器打印日志的策略子类
    class ConsoleLogStrategy : public LogManage
    {
    public:
        ConsoleLogStrategy()
        {
        }
        void Synclog(const std::string &message) override
        {
            _mutex.Lock();
            std::cout << message << gsep;
            _mutex.Unlock();
        }
        ~ConsoleLogStrategy()
        {
        }

    private:
        Mutex _mutex;
    };
    // 文件打印日志的策略 : 子类
    const std::string defaultpath = "./log";
    const std::string defaultfile = "my.log";
    class FileLogStrategy : public LogManage
    {
    public:
        FileLogStrategy(const std::string &path = defaultpath, const std::string &name = defaultfile)
            : _path(path), _name(name)
        {
            LockGuard Lock(_mutex);
            // 构造时检查路径是否合法存在，若不合法存在则创建路径
            if (std::filesystem::exists(_path))
            {
                return;
            }
            // 创建路径
            try
            {
                std::filesystem::create_directories(_path);
            }
            catch (const std::filesystem::filesystem_error &e)
            {
                std::cerr << e.what() << '\n';
            }
        }
        void Synclog(const std::string &message) override
        {
            LockGuard  Lock(_mutex);
            std::string filename = _path + (_path.back() == '/' ? "" : "/") + _name;
            std::ofstream out(filename, std::ios::app); // 以追加的方式打开文件
            if (!out.is_open())
            {
                return;
            }
            out << message << gsep;
            out.close();
        }
        ~FileLogStrategy()
        {
        }

    private:
        std::string _path;
        std::string _name;
        Mutex _mutex;
    };


    // 形成一条完整的日志&&根据上面的策略，选择不同的刷新方式

    // 1. 形成日志等级
    enum class loglevel
    {
        DEBUG,
        INFO,
        WARNING,
        ERROR,
        FATAL
    };
    std::string Level2Str(loglevel level)
    {
        switch (level)
        {
        case loglevel::DEBUG:
            return "DEBUG";
        case loglevel::INFO:
            return "INFO";
        case loglevel::WARNING:
            return "WARNING";
        case loglevel::ERROR:
            return "ERROR";
        case loglevel::FATAL:
            return "FATAL";
        default:
            return "UNKNOWN";
        }
    }
    std::string GetTimeStamp()//获取时间
    {
        time_t t = time(nullptr);
        struct tm _t;
        localtime_r(&t, &_t);
        char timebuffer[128];
        snprintf(timebuffer, sizeof(timebuffer), "%4d-%02d-%02d %02d:%02d:%02d",
                 _t.tm_year + 1900,
                 _t.tm_mon + 1,
                 _t.tm_mday,
                 _t.tm_hour,
                 _t.tm_min,
                 _t.tm_sec);
        return timebuffer;
    }
    // 1. 形成日志 && 2. 根据不同的策略，完成刷新
    class Loger
    {
    public:
        Loger()
        {
            EnableConsoleLogStrategy();//
        }
        void EnableFileLogStrategy() // 向文件显示
        {
            _fflush_strategy = std::make_unique<FileLogStrategy>();
        }
        void EnableConsoleLogStrategy()
        {
            _fflush_strategy = std::make_unique<ConsoleLogStrategy>();
        }
        // 表示的是未来的一条日志形成结构体系
        class LogerMessage
        {
        public:
            LogerMessage(loglevel& level,std::string &src_name,int linenumber,Loger& loger)
            :_curr_time(GetTimeStamp())
            ,_level(level)
            ,_pid(getpid())
            ,_src_name(src_name)
            ,_line_number(linenumber)
            ,_loger(loger)
            {
                std::stringstream ss;
                ss<<"[" << _curr_time << "] "
                   << "[" << Level2Str(_level) << "] "
                   << "[" << _pid << "] "
                   << "[" << _src_name << "] "
                   << "[" << _line_number << "] "
                   << "- ";
                   _loginfo = ss.str();
            }
            template <class T>
            LogerMessage& operator<<(const T &info)
            {
                // 日志的右半部分,可变的
                std::stringstream ss;
                ss << info;
                _loginfo += ss.str();
                return *this;
            }
            ~LogerMessage()
            {
                if (_loger._fflush_strategy)
                {
                    _loger._fflush_strategy->Synclog(_loginfo);
                }
            }

        private:
            std::string _curr_time;
            loglevel _level;
            pid_t _pid;
            std::string _src_name;
            int _line_number;
            std::string _loginfo; // 合并之后，一条完整的信息
            Loger &_loger;
        };
         // 返回临时对象
        LogerMessage operator()(loglevel level, std::string name, int line)
        {
            return LogerMessage(level, name, line, *this);
        }
        ~Loger()
        {
        }

    private:
        std::unique_ptr<LogManage> _fflush_strategy;
    };
    // 全局日志对象
    Loger logger;

    // 使用宏，简化用户操作，获取文件名和行号
    #define LOG(level) logger(level, __FILE__, __LINE__)
    #define Enable_Console_Log_Strategy() logger.EnableConsoleLogStrategy()
    #define Enable_File_Log_Strategy() logger.EnableFileLogStrategy()
}
